//
//  ADJgSDKNativeAdapter.m
//  AnyThinkSDKDemo
//
//  Created by 刘娟 on 2024/9/25.
//  Copyright © 2024 抽筋的灯. All rights reserved.
//

#import "ADJgSDKNativeAdapter.h"
#import <ADJgSDK/ADJgSDK.h>
#import "ADJgSDKNativeCustomEvent.h"
#import "ADJgSDKNativeRenderer.h"
#import <AnyThinkNative/AnyThinkNative.h>
#import "ADJgSDKNativeAdContainer.h"
#import "ATADJgSDKBiddingRequest.h"
#import "ATADJgSDKBiddingManager.h"
@interface ADJgSDKNativeAdapter ()

@property(nonatomic, readonly) ADJgSDKNativeAd *adMgr;

@property(nonatomic, readonly) ADJgSDKNativeCustomEvent *customEvent;

@property(nonatomic, strong)ADJgSDKNativeAdContainer *nativeAdContainer;

@end

@implementation ADJgSDKNativeAdapter

+(Class) rendererClass {
    return [ADJgSDKNativeRenderer class];
}

-(instancetype) initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo {
    self = [super init];
    if (self != nil) {
        if (![[ATAPI sharedInstance] initFlagForNetwork:@"ADJgSDK"]) {
            [[ATAPI sharedInstance] setInitFlagForNetwork:@"ADJgSDK"];
            [ADJgSDK initWithAppId:serverInfo[@"app_id"] completionBlock:^(NSError * _Nullable error) {
                if(error){
                    [[ATAPI sharedInstance] setInitFlag:0 forNetwork:@"ADJgSDK"];
                    NSLog(@"ADJgSDK - 初始化失败：%@",error);
                }
            }];
        }
       
    }
    return self;
}

-(void) loadADWithInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo completion:(void (^)(NSArray<NSDictionary *> *, NSError *))completion {
    dispatch_async(dispatch_get_main_queue(), ^{
        self->_customEvent = [ADJgSDKNativeCustomEvent new];
        self->_customEvent.requestCompletionBlock = completion;
        NSDictionary *extraInfo = localInfo;

        CGSize size = CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds) - 30.0f, 200.0f);
        if ([extraInfo[kATExtraInfoNativeAdSizeKey] respondsToSelector:@selector(CGSizeValue)]) {
           size = [extraInfo[kATExtraInfoNativeAdSizeKey] CGSizeValue];
        }
        
        NSString *bidId = serverInfo[kATAdapterCustomInfoBuyeruIdKey];
        if (bidId.length) {
            
            ATADJgSDKBiddingRequest *request = [[ATADJgSDKBiddingManager sharedInstance] getRequestItemWithUnitID:serverInfo[@"slot_id"]];
            
            if (request.customObject!=nil) { // load secced
                self.nativeAdContainer = request.customObject;
                self.nativeAdContainer.delegate = self->_customEvent;
                self->_customEvent.nativeAdContainer = self.nativeAdContainer;
                self->_customEvent.requestCompletionBlock(self.nativeAdContainer.assets, nil);
            } else { // fail
                NSError *error = [NSError errorWithDomain:ATADLoadingErrorDomain code:-1000001 userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load intertitial.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}];
                [self->_customEvent trackNativeAdLoadFailed:error];
            }
            [[ATADJgSDKBiddingManager sharedInstance] removeRequestItmeWithUnitID:serverInfo[@"slot_id"]];
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self->_customEvent loadNativeWithPosId:serverInfo[@"slot_id"] Count:1 size:size];

            });
        }
    });
}
#pragma mark - Header bidding
#pragma mark - c2s
+(void)bidRequestWithPlacementModel:(ATPlacementModel*)placementModel unitGroupModel:(ATUnitGroupModel*)unitGroupModel info:(NSDictionary*)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion {
    NSLog(@"%s", __FUNCTION__);
    if (NSClassFromString(@"ADJgSDK") == nil) {
        if (completion != nil) { completion( nil, [NSError errorWithDomain:@"com.ubix.mediation.ios" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Bid request has failed", NSLocalizedFailureReasonErrorKey:@"ADJgSDK is not imported"}]); }
        return;
    }
   
    
    if (![[ATAPI sharedInstance] initFlagForNetwork:@"ADJgSDK"]) {
        [[ATAPI sharedInstance] setInitFlagForNetwork:@"ADJgSDK"];
        [ADJgSDK initWithAppId:info[@"app_id"] completionBlock:^(NSError * _Nullable error) {
            if (error){
                [[ATAPI sharedInstance] setInitFlag:0 forNetwork:@"ADJgSDK"];
                NSLog(@"ADJgSDK - 初始化失败%@",error);
            } else {
                CGSize size = CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds) - 30.0f, 200.0f);
                
    //
                ATADJgSDKBiddingManager *biddingManage = [ATADJgSDKBiddingManager sharedInstance];
                ATADJgSDKBiddingRequest *request = [ATADJgSDKBiddingRequest new];
                request.unitGroup = unitGroupModel;
                request.placementID = placementModel.placementID;
                request.bidCompletion = completion;
                request.unitID = info[@"slot_id"];
                request.extraInfo = info;
                request.adType = ESCAdFormatNative;
                ADJgSDKNativeAdContainer *nativeAdContainer = [[ADJgSDKNativeAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil size:size];
                request.customObject = nativeAdContainer;
                [biddingManage startWithRequestItem:request];
                [nativeAdContainer loadNativeAdWithCount:1];
            }
        }];
                
    }else{
        CGSize size = CGSizeMake(CGRectGetWidth([UIScreen mainScreen].bounds) - 30.0f, 200.0f);
        ATADJgSDKBiddingManager *biddingManage = [ATADJgSDKBiddingManager sharedInstance];
        ATADJgSDKBiddingRequest *request = [ATADJgSDKBiddingRequest new];
        request.unitGroup = unitGroupModel;
        request.placementID = placementModel.placementID;
        request.bidCompletion = completion;
        request.unitID = info[@"slot_id"];
        request.extraInfo = info;
        request.adType = ESCAdFormatNative;
        ADJgSDKNativeAdContainer *nativeAdContainer = [[ADJgSDKNativeAdContainer alloc] initPosId:info[@"slot_id"] delegate:nil size:size];
        request.customObject = nativeAdContainer;
        [biddingManage startWithRequestItem:request];
        [nativeAdContainer loadNativeAdWithCount:1];
    }
}


+ (void) sendWinnerNotifyWithCustomObject:(id)customObject secondPrice:(NSString*)price userInfo:(NSDictionary<NSString *, NSString *> *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    ADJgSDKNativeAdContainer *nativeAdContainer = (ADJgSDKNativeAdContainer *)customObject;
#if DEBUG
    NSLog(@"ADJgSDK - 信息流 - 上报竞赢价格：%ld",[nativeAdContainer getBidPrice]);
#endif
}

+ (void)sendLossNotifyWithCustomObject:(nonnull id)customObject lossType:(ATBiddingLossType)lossType winPrice:(nonnull NSString *)price userInfo:(NSDictionary *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    //美元转人民币，转换为分
    CGFloat cnyPrice = price.floatValue * 6.3 * 100;
    ADJgSDKNativeAdContainer *nativeAdContainer = (ADJgSDKNativeAdContainer *)customObject;    
#if DEBUG
    NSLog(@"ADJgSDK - 信息流 - 上报竞败；竞赢价格：%ld",@(cnyPrice).integerValue);
#endif
}

@end
